﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using BbsbWebService.Enums;
using System.ServiceModel.Description;
using BbsbWebService.Service.Callback;
using System.Windows.Forms;
using BbsbWebService.Classes;

namespace BbsbWebService.Service.Update
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class BbsbUpdateService : IBbsbUpdateService
    {
        ServiceHost _host;
        List<IBbsbUpdateCallback> _channels = new List<IBbsbUpdateCallback>();

        #region IBbsbUpdateService Members

        public void RegisterListener()
        {
            _channels.Add(OperationContext.Current.GetCallbackChannel<IBbsbUpdateCallback>());
        }

        #endregion

        public void Initialise()
        {
            Uri uri = new Uri(ApplicationState.LocalMachine.ToBbsbUpdateAddress());

            _host = new ServiceHost(this, uri);
            WSDualHttpBinding binding = new WSDualHttpBinding
            {
                Security = new WSDualHttpSecurity
                {
                    Mode = WSDualHttpSecurityMode.None
                }
            };

            _host.AddServiceEndpoint(typeof(IBbsbUpdateService), binding, string.Empty);
            _host.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
            
            _host.Open();
        }

        public void UpdateState(Guid id, BbsbWebService.Enums.PowerState state)
        {
            foreach (var channel in _channels)
            {
                Callback.PowerState newState = (BbsbWebService.Service.Callback.PowerState)((int)state);

                try
                {
                    channel.StateUpdated(id, newState);
                }
                catch (Exception ex)
                {
                    Logging.Logger.Instance.LogException(ex, "Failed to send state update to client");
                }
            }
        }
    }
}
